const InspireCloud = require('@byteinspire/js-sdk') //详情看https://qingfuwu.cn/docs/nodejs/api/file.html#%E5%AE%A2%E6%88%B7%E7%AB%AF
const serviceId = 'qcx4z8';
const fileUploadToken = '689820e7-0aef-4a5d-a12b-24bd4d6b00db'; // 替换成你的客户端上传 token
const inspirecloud = new InspireCloud({ serviceId });
const {userTable,ObjectId} = require('../models/user');
const publicImgTable = require('../models/publicImg')
const jwt = require('jsonwebtoken')

// import {nanoid} from 'nanoid'

class userService {
    async register(ctx) {
        // console.log(ctx.request.body);
        const { username, password, email } = ctx.request.body
        //判断是否注册
        const model = await userTable.where({ username: username }).findOne()
        if (model) {
            ctx.response.status = 201;
            return {
                data: {
                    model
                },
                meta: {
                    msg: '用户名已存在!',
                    status: 400
                }
            }
        }
        //创建用户
        const createUser = await userTable.save({ 
            username: username, 
            password: password,
            nickname: `用户${username}`,
            sex: true,
            avater:'https://img0.baidu.com/it/u=1329709505,2760911286&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=800',
            profile: '该用户很懒,没有做自我介绍',
            email: '该用户没有留下邮箱地址',
            date: '未知',
            age: 18,
        })
        ctx.response.status = 201;
        return {
            data: {
                createUser
            },
            meta: {
                msg: '注册成功!',
                status: 201
            }
        }
    }
    async login(ctx) {
        const { username, password } = ctx.request.body
        // console.log(ctx);
        // console.log('这是用户名和密码', ctx.request.body);

        //根据用户名来查询数据库是否存在这个用户
        const findUser = await userTable.where({ username: username }).findOne()
        // console.log(findUser)
        if (!findUser) {
            ctx.response.status = 200;
            return {
                data: {
                    findUser: null
                },
                meta: {
                    msg: "用户名不存在!",
                    status: 400
                }
            }
        }
        //判断账号和密码是否正确
        if (username != findUser.username || password != findUser.password) {
            ctx.response.status = 200;
            return {
                data: {
                    findUser: findUser
                },
                meta: {
                    msg: "账号或密码不正确!",
                    status: 400
                }
            }
        }
        const token = jwt.sign({ username }, 'yt', { expiresIn: '1h' })
        console.log(findUser);
        ctx.response.status = 200;
        return {
            data: {
                userInfo: findUser,
                token
            },
            meta: {
                msg: "登陆成功!",
                status: 200
            }
        }
    }
    async savaRegister(ctx){
        // const {_id,nickname,sex,avater,profile}
    }
    async editor(ctx) {
        const { _id, nickname, sex, age, profile, email, date, username,imageUrl } = ctx.request.body
        // console.log('从修改页拿到的数据', _id, nickname, sex, age, profile, email, date);
        const findUser = await userTable.where({ username: username }).findOne()
        findUser.nickname = nickname ? nickname : findUser.nickname;
        findUser.sex = sex ? sex : findUser.sex;
        findUser.age = age ? age : findUser.age;
        findUser.profile = profile ? profile : findUser.profile;
        findUser.date = date ? date : findUser.date;
        findUser.email = email ? email : findUser.email;
        findUser.avater = imageUrl ? imageUrl : findUser.avater
        const result = await userTable.save(findUser);
        console.log(result);
        ctx.response.status = 200;
        return {
            data: {
                userInfo: result
            },
            meta: {
                status: 200,
                msg: '修改成功!'
            }
        }
    }
    async fileImg(ctx) {
        let file = ctx.request.files ? ctx.request.files.file : {}
        const { url } = await inspirecloud.file.upload(`${file.name}`, file, { token: fileUploadToken })
        if (url) {
            ctx.status = 200
            return {
                data: {
                    url
                },
                meta: {
                    msg: '上传成功',
                    status: 200
                }
            }
        } else {
            ctx.status = 500
            return {
                msg: '服务器发生不可描述的错误'
            }
        }

    }
    async publicImg(ctx) {
        const { content, image, id, avater, nickname } = ctx.request.body
        // console.log(ctx.request.body, '---id---');
        const good = 0
        const createContent = await publicImgTable.save({ content, image, id, avater, nickname ,good })
        ctx.response.status = 201;
        return {
            data: {
                createContent
            },
            meta: {
                msg: '发布成功!',
                status: 201
            }
        }
    }


    async getmessages(ctx){
        //获取所有的数据
        const userMessages = await publicImgTable.where().find()
        // console.log('这是发布表的数据',userMessages);
        ctx.response.status = 200
        return {
            data: {
                userMessages: userMessages
            },
            meta: {
                status: 200,
                msg: '得到成功'
            }
        }
    }


    async getOnlyMessage(ctx){
        const { _id } = ctx.request.body
        const res = await publicImgTable.where({_id : ObjectId(_id)}).findOne()
        ctx.response.status = 200
        return{
            data:{
                OnlyMessage: res
            },
            msg:{
                status:200,
                msg:'获取文章信息成功!'
            }
        }
    
    }


    async ownerMessages(ctx){
        const { _id } =  ctx.request.body
        const res = await publicImgTable.where({id: _id}).find()
        const userInfo = await userTable.where({ _id: ObjectId(_id)}).findOne()
        // console.log('查询到的记录',res);
        return {
            data: {
                ownerMessages:  res,
                userInfo: userInfo
            },
            meta: {
                status: 200,
                msg: '获取个人发布记录和个人信息成功!'
            }
        }
    }
    async allUsers(ctx) {
        const skip = ctx.request.body.skip
        const data = await userTable.where().projection({ password: 0 }).skip(skip).limit(3).find()
        if (data) {
            // console.log('some two', data);
            return {
                data,
                status: 200
            }
        } else {
            console.log('some One');
            return {
                msg: '没有更多数据了~',
                status: 504
            }
        }

    }
    async test(ctx) {
        const { id } = ctx.request.body
        console.log(id, '0----0');
        const data = await userTable.where({ _id: ObjectId(id) }).findOne();
        console.log(data, 'data');
        return data
    }

    async addGood(ctx){
        const {_id} = ctx.request.body
        const res = await publicImgTable.where({_id: ObjectId(_id)}).findOne()
        // console.log('这是推文具体信息',res);
        res.good = res.good + 1
        const result = await publicImgTable.save(res)
        ctx.response.status = 200
        return {
            data: {
                res: result
            },
            meta: {
                status: 200,
                msg: '获取推文具体信息成功'
            }
        }
    }
    async removeGood(ctx) {
        const { _id } = ctx.request.body
        const res = await publicImgTable.where({ _id: ObjectId(_id) }).findOne()
        // console.log('这是推文具体信息', res);
        res.good = res.good - 1
        const result = await publicImgTable.save(res)
        ctx.response.status = 200
        return {
            data: {
                res: result
            },
            meta: {
                status: 200,
                msg: '减去点赞成功'
            }
        }
    }
    async deletePublicImg(ctx) {
            const { url } = ctx.request.body
            console.log(url, '111---111');
            const data = await fileTable.where({ url }).find();
            // 使用 delete 删除这些记录
            const result = await fileTable.delete(data);
            console.log(result, 'result');
            ctx.response.status = 200
            return {
                msg: '删除成功',
                status: 200
            }
        }

    async addAttention(ctx){
        const { _id , others } = ctx.request.body
        const res = await userTable.where({_id : ObjectId(_id)}).findOne()
        // console.log('拿到关注表的具体信息',res);
        res.attention = others
        const result = await userTable.save(res)
        ctx.response.status = 200
        return {
            data: {
                userInfo : result
            },
            meta: {
                status: 200,
                msg: '关注表添加成功'
            }
        }
    }

    //  查找所有已关注的用户
    async searchAttention(ctx){
        const {_id} = ctx.request.body
        const res = await userTable.where({_id: ObjectId(_id)}).findOne()
        const { attention } = res
        console.log(attention,'11111111111');
        ctx.response.status = 200
        return {
            data: {
                allAttention: attention
            },
            msg: {
                status: 200,
                msg: '查找到所有已关注的用户'
            }
        }
        
    }

    async searchComment(ctx){
        // _id是推文本身的_id
        const {_id} = ctx.request.body
        const res = await publicImgTable.where({_id: ObjectId(_id)}).findOne()
        const { Comments } = res
        // console.log(res.Comments,'找到评论数据');
        ctx.response.status = 200
        return {
            data: {
                userInfo : Comments
            },
            meta: {
                status: 200,
                msg: '评论查找成功'
            }
        }
    }

    async addComment(ctx){
        // _id是推文本身的_id
        const { _id, others } = ctx.request.body
        const res = await publicImgTable.where({_id: ObjectId(_id)}).findOne()
        res.Comments = others
        const result = await publicImgTable.save(res)
        console.log('保存后的数据',result);
        ctx.response.status = 200
        return {
            data: {
                Comments: result
            },
            meta: {
                status: 200,
                msg: '添加评论成功!'
            }
        }
    }

    
}



module.exports = new userService();